<template>
	<view class="container">
		<view class="status_bar">
			<view style="margin-left: 4%;" @tap="goBack()"><u-icon name="arrow-leftward" size='24' /></view>
			<view style="margin-left: -50upx; font-weight: bold;">账号设置</view>
			<view></view>
			</u-icon>
		</view>
		<!--头部-->

		<!-- <view @tap="uploadFace" class="items flex-row">
			<text class="label">头像</text>
			<view class="flex-row">
				<image v-if="user.face" :src="user.face" class="face"></image>
				<image v-else src="../../static/img/face.png" class="face"></image>
				<uni-icons type="arrowright" size="18" color="#999"></uni-icons>
			</view>
		</view> -->
		<view class="shop-box">
			<view class="con-shop" @tap="uploadFace">
				<view style="display: flex;">
					<view style="margin-top: 10upx;">头像</view>
				</view>
				<view class="flex-row">
					<image v-if="userInfo.user_avatar_file_name"
						:src="`http://chat.zwsmcn.com:8090/UserAvatarDownloader?action=ad&user_uid=${userInfo.user_uid}&user_local_cached_avatar=${userInfo.user_avatar_file_name}&enforceDawnload=1&token=`"
						class="face">
					</image>
					<image v-else src="../../../static/img/face.png" class="face"></image>
					<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
				</view>

			</view>
			<view class="con-shop" @tap="toPage(`/pages/mine/account/nicknameUpdate?type=nickname`)">
				<view style="display: flex;">
					<view style="margin-top: 10upx;">昵称</view>
				</view>
				<view>
					<span style="padding-right: 10upx; color: #b5b5b5;">{{userInfo.nickname}}</span>
					<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
				</view>
			</view>
			<view class="con-shop" @tap="handlePickSex()">
				<view style="display: flex;">
					<view style="margin-top: 10upx;">性别</view>
				</view>
				<view>
					<span style="padding-right: 10upx; color: #b5b5b5;">{{userInfo.user_sex==1?"男":"女"}}</span>
					<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
					<u-picker :show="showSex" :columns="columns" keyName="label" @cancel="cancelSex"
						@confirm="confirmSex"></u-picker>
				</view>


			</view>
			<view class="con-shop" @tap="toPage(`/pages/mine/account/nicknameUpdate?type=nickname？type=brief`)">
				<view style="display: flex;">
					<view style="margin-top: 10upx;">个人介绍</view>
				</view>
				<view>
					<span
						style="padding-right: 10upx; color: #b5b5b5;">{{userInfo.user_desc?userInfo.user_desc:"未填写"}}</span>
					<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
				</view>
			</view>

		</view>
		<view class="shop-box">
			<view class="con-shop" @tap="toPage('/pages/mine/account/phoneUpdate')">
				<view style="display: flex;">
					<view style="margin-top: 10upx;">手机</view>
				</view>
				<view>
					<span style="padding-right: 10upx; color: #b5b5b5;">153****0797</span>
					<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
				</view>
			</view>
			<view class="con-shop" @tap="toPage('/pages/mine/account/passwordUpdate')">
				<view style="display: flex;">
					<view style="margin-top: 10upx;">修改登录密码</view>
				</view>
				<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
			</view>
			

		</view>
		<view class="shop-box">
			<view class="con-shop" @tap="toPage('/pages/mine/account/qrCode')">
				<view style="display: flex;">
					<image src="../../../static/image/user/1@3x.png" class="image-code"></image>
					<view style="margin-top: 10upx;">我的二维码</view>
				</view>
				<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
			</view>
			<!-- <view class="con-shop" @tap="showDate = true">
				<view style="display: flex;">
					<image src="../../../static/image/user/2@3x.png" class="image-code"></image>
					<view style="margin-top: 10upx;">生日</view>
				</view>
				<view>
					<span style="padding-right: 10upx; color: #b5b5b5;">未设置</span>
					<uni-icons type="arrowright" size="18" color="#eaeaea"></uni-icons>
				</view>
			</view> -->
		</view>
		<view class="bottom-box">
			<view class="tab-num" @tap="logouta">
				<image src="../../../static/image/user/4@3x.png" class="image-code"></image>
				<span>切换账号</span>
			</view>
			<view class="tab-num" style="background-color: #fd2d2b;" @click="logout">
				<image src="../../../static/image/user/3@3x.png" class="image-code"></image>
				<span>退出登录</span>
			</view>
		</view>
		<view>
			<u-calendar :show="showDate" @confirm="confirm" @close="close" color="#674fa3"></u-calendar>
		</view>

		<!-- <view @tap="logout" class="main-btn flex-column">退出登录</view> -->

		<!--修改名称-->
		<uni-popup ref="edit">
			<view class="dialog">
				<view class="title">我的昵称</view>
				<input class="input" v-model="nickname" type="text" placeholder="请输入群聊名称" />
				<view @tap="editAction" class="btn" :class="{disabled: !nickname}">完成</view>
				<view @tap="cancelEdit" class="close">
					<uni-icons type="closeempty" size="26" color="#999"></uni-icons>
				</view>
			</view>
		</uni-popup>


		<kps-image-cutter v-if="tailorshow" @ok="onok" @cancel="oncancle" :url="url" :fixed="true" :blob="false"
			:width="200" :height="200" :maxWidth="500" :maxHeight="500"></kps-image-cutter>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userId: uni.getStorageSync('userId') || '',
				startX: 0, // 触摸开始的X坐标
				endX: 0, // 触摸结束的X坐标
				threshold: 50, // 设置滑动多少距离后触发返回
				user: {},
				userInfo: {},
				nickname: '',

				text1: 'uView UI众多组件覆盖开发过程的各个需求，组件功能丰富，多端兼容。让您快速集成，开箱即用',
				showSex: false,
				columns: [
					[{
						label: '男',
						id: 2021
					}, {
						label: '女',
						id: 804
					}]
				],
				showDate: false,


				url: "",
				path: "",
				tailorshow: false,
			}
		},
		onLoad() {
			//this.getDetail()
		},
		onShow() {
			this.getUser()
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},


			handlePickSex() {
				this.showSex = true
			},
			cancelSex() {
				this.showSex = false
			},
			confirmSex(e) {
				console.log('confirm', e.value[0].label)
				let user_sex = e.value[0].label == "男" ? 1 : 0
				this.handleUserUpdate(user_sex)
				this.getUser()
				this.showSex = false
			},
			confirm(e) {
				console.log(e);
				this.showDate = false
			},
			close() {
				this.showDate = false
			},
			logout() {
				// 

				// 清除名为userInfo的缓存数据
				// uni.removeStorageSync('user_uid');
				uni.showModal({
					title: '',
					content: '确定要退出吗？',
					cancelColor: '#000',
					confirmColor: '#40AFFE',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							uni.setStorageSync('loginInfo', {});
							uni.setStorageSync('token', '')
							uni.setStorageSync('user_uid', '')
							uni.setStorageSync('userId', '')
							uni.setStorageSync('user_level', '')
							uni.setStorageSync('nickname', '')
							uni.setStorageSync('user_avatar_file_name', '')
							uni.setStorageSync('loginInfoArr', []);
							uni.IMSDK.disconnectSocket();
							uni.MBSocketProvider.closeLocalSocket();
							
							this.toPage('/pages/login')
						} else if (res.cancel) {}
					}
				});
				
				
				// LocalUDPDataSender.sendLoginout()
			},
			logouta() {
				uni.navigateTo({
					url: '/pages/mine/account/qihuan'
				});
			},
			showEdit() {
				this.groupName = this.group.name
				this.$refs.edit.open()
			},
			cancelEdit() {
				this.$refs.edit.close()
			},
			editAction() {
				if (this.$validate.isNull(this.groupName)) return

				uni.request({
					method: 'POST',
					url: this.$api.updateGroupName,
					data: {
						groupId: this.groupId,
						userId: this.userId,
						name: this.groupName
					},
					header: this.$util.getHeader(),
					success: res => {
						uni.hideLoading()
						this.$util.toast(res.data.msg)
						if (!res.data.code) {
							this.$refs.edit.close()
							this.group.name = this.groupName
							uni.setStorageSync('groupName', this.groupName)
						}
					},
					fail: res => {
						uni.hideLoading()
						this.$util.toast('保存失败')
					}
				})
			},
			// 上传头像
			// uploadFace() {
			// 	uni.chooseImage({
			// 		count: 1, // 限制只选择一张图片
			// 		success: chooseRes => {
			// 			const tempFilePath = chooseRes.tempFilePaths[0]; // 获取选中的图片路径
			// 			console.log('选择的图片路径:', tempFilePath);

			// 			// 获取文件名
			// 			const fileName = tempFilePath.substring(tempFilePath.lastIndexOf('/') + 1);

			// 			// 构建 GET 请求 URL
			// 			const userId = uni.getStorageSync('userId'); // 获取用户 ID
			// 			const encodedFileName = encodeURIComponent(fileName); // 对文件名进行 URL 编码
			// 			const encodedFilePath = encodeURIComponent(tempFilePath); // 对文件路径进行 URL 编码

			// 			const url =
			// 				`http://chat.zwsmcn.com:8090/UserAvatarUploader?action=2&user_uid=${userId}&file_name=${encodedFileName}&file=${encodedFilePath}`;

			// 			// 发起 GET 请求
			// 			this.sendGetRequest(url);
			// 		},
			// 		fail: err => {
			// 			console.error('图片选择失败:', err);
			// 		}
			// 	});
			// },
			onok(ev) {
				//console.log(ev);

				let img = ev.path;
				this.url = "";

				let Paths = this.$md5(img);
				let Filetype = img.substring(img.lastIndexOf('.'));
				let files = {
					file_name: Paths + Filetype,
				}
				plus.io.resolveLocalFileSystemURL(
					img,
					entry => { //获取文件对象  
						console.log("entry:" + entry.fullPath);
						plus.io.resolveLocalFileSystemURL(
							"_downloads",
							entry22 => { //获取文件对象  
								console.log("entry223:" + entry22.fullPath);
								var nname = Paths + Filetype
								entry.copyTo(entry22, nname, newimage => {
										console.log("808");
										console.log(newimage.fullPath);
										this.uploadMsgImage('file://' + newimage
											.fullPath, nname);

									},
									newimage => {
										console.log("808err");
										console.log(newimage);
									});


							}
						)



					}
				)
			},
			oncancle() {
				//console.log(11);
				// url设置为空，隐藏控件
				this.url = "";
			},
			// 发送图片
			uploadFace() {
				uni.chooseImage({
					sourceType: ['album', 'camera'],
					count: 1, // 限制只选择一张图片
					success: chooseImageRes => {
						const tempFilePaths = chooseImageRes.tempFilePaths;


						this.url = tempFilePaths[0];

						console.log(this.url);
						this.tailorshow = true;
						//console.log(this.img);
						this.imgpath = '';

						return;

						console.log(tempFilePaths);
						let Paths = this.$md5(tempFilePaths[0]);
						let Filetype = tempFilePaths[0].substring(tempFilePaths[0].lastIndexOf('.'));
						let files = {
							file_name: Paths + Filetype,
						}
						plus.io.resolveLocalFileSystemURL(
							tempFilePaths[0],
							entry => { //获取文件对象  
								console.log("entry:" + entry.fullPath);
								plus.io.resolveLocalFileSystemURL(
									"_downloads",
									entry22 => { //获取文件对象  
										console.log("entry223:" + entry22.fullPath);
										var nname = Paths + Filetype
										entry.copyTo(entry22, nname, newimage => {
												console.log("808");
												console.log(newimage.fullPath);
												this.uploadMsgImage('file://' + newimage
													.fullPath, nname);

											},
											newimage => {
												console.log("808err");
												console.log(newimage);
											});


									}
								)



							}
						)


					}
				})
			},
			uploadMsgImage(filePath, nname) {
				uni.uploadFile({

					url: 'http://chat.zwsmcn.com:8090/UserAvatarUploader',
					header: {
						'content-type': 'multipart/form-data',
					},
					filePath: filePath,
					name: nname, //'file',
					formData: {
						user_uid: uni.getStorageSync('userId'),
						file_name: nname,
					},
					method: 'post',
					success: res => {
						console.log(res)
						if (res.statusCode == 200) {
							this.getUser();
							
							let avatar = `http://chat.zwsmcn.com:8090/UserAvatarDownloader?action=ad&user_uid=${this.userInfo.user_uid}&user_local_cached_avatar=${nname}&enforceDawnload=1&token=`
							this.handleUseravatar(avatar);
							console.log(0, "===================")
						}
					},
					fail: res => {
						console.log(res);
					}
				});
				return;
				// this.$util.loading('上传中')

			},


			sendGetRequest(url) {
				uni.request({
					url,
					method: 'GET',
					success: res => {
						uni.hideLoading(); // 隐藏加载提示
						console.log('请求成功:', res);

						try {
							const imgItem = JSON.parse(res.data); // 尝试解析返回数据
							console.log('返回的图片数据:', imgItem);

							if (imgItem && imgItem.data && imgItem.data.url) {
								this.handleUseravatar(imgItem.data.url); // 更新头像
								this.$forceUpdate(); // 强制视图更新
							} else {
								console.error('返回数据格式不正确:', imgItem);
							}
						} catch (error) {
							console.error('数据解析失败:', error);
						}
					},
					fail: err => {
						uni.hideLoading();
						console.error('请求失败:', err);
					}
				});
			},


			getUser() {
				uni.request({
					url: this.$api.baseUrl + '/api/user/detail',
					header: {
						'content-type': 'application/json'
					},
					data: {
						user_uid: uni.getStorageSync('user_uid'),
					},
					method: 'POST',
					success: res => {
						console.log(res, 'res');
						// uni.hideLoading()
						if (res.data.code == 0) {
							this.userInfo = res.data.data
							this.$forceUpdate();
						}
						console.log(this.userInfo);
						// this.list = res.data;
					},
					fail: res => {
						console.log(res);
					}

				})
			},
			handleUseravatar(avatar) {
				console.log(avatar);
				uni.request({
					url: this.$api.baseUrl + '/api/user/update',
					header: {
						'content-type': 'application/json'
					},
					data: {
						user_uid: uni.getStorageSync('user_uid'),
						avatar: avatar
					},
					method: 'POST',
					success: res => {
						console.log(res, 'res');
						// uni.hideLoading()
						if (res.data.code == 0) {
							// uni.navigateBack();

							this.$util.toast(res.data.message)
							this.getUser();
						}
						console.log(this.list);
						// this.list = res.data;
					},
					fail: res => {
						console.log(res);
					}

				})
			},
			handleUserUpdate(user_sex) {
				uni.request({
					url: this.$api.baseUrl + '/api/user/update',
					header: {
						'content-type': 'application/json'
					},
					data: {
						user_uid: uni.getStorageSync('user_uid'),
						user_sex: user_sex
					},
					method: 'POST',
					success: res => {
						console.log(res, 'res');
						// uni.hideLoading()
						if (res.data.code == 0) {
							// uni.navigateBack();


							this.$util.toast(res.data.message)
							this.getUser();
						}
						console.log(this.list);
						// this.list = res.data;
					},
					fail: res => {
						console.log(res);
					}

				})
			},
			// 获取头像
			getDetail() {
				const requestDataJsonStr = JSON.stringify(requestData);
				uni.request({
					url: `http://192.168.1.190:8080/http://192.168.1.190:8080/UserAvatarDownloader?action=ad&user_uid=400070&user_local_cached_av atar=400070_91c3e0d81b2039caa9c9899668b249e8.jpg&enforceDawnload=0`,

					header: {
						'content-type': 'application/json'
					},
					data: requestDataJsonStr,
					method: 'POST',
					success: res => {
						S
						this.saveShow = false
					},
					fail: res => {
						console.log(res);
					}
				});
			}

		}
	}
</script>

<style lang="scss" scoped>
	page {
		// background-color: #999;
		overflow: hidden;
	}

	.container {
		width: 100%;
		height: 100%;

	}

	.status_bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 50upx;
	}

	.status_bar,
	.head {
		background-color: #fff;
		height: 160upx;

		.face {
			width: 160upx;
			height: 160upx;
			border-radius: 10upx;
		}

		.info-name {
			font-size: 40upx;
			font-weight: bold;
		}

		.info-num {
			// width: 56upx;
			padding: 2upx 30upx;
			background: #f0f4f7;
			border-radius: 30upx;
			margin-top: 21upx;
		}

		.copybtns {
			color: #4457a4;
			margin-top: 21upx;
		}
	}

	.items {
		height: 100upx;
		padding: 0 30upx;
		background-color: #FFF;
		border-bottom: 2upx solid #F2F2F2;

		.label {
			color: #666;
			font-size: 32upx;
		}

		.value {
			color: #999;
			font-size: 30upx;
		}

		.face {
			width: 100upx;
			height: 100upx;
			border-radius: 10upx;
		}
	}

	.main-btn {
		color: red;
		height: 100upx;
		padding: 0 30upx;
		margin-top: 100upx;
		background-color: #FFF;
	}

	.shop-box {
		width: 92%;
		margin-left: 4%;
		background-color: #fff;
		margin-top: 20upx;
		border-radius: 20upx;
		padding: 10upx 30upx;
		box-shadow: 0 0 40upx #d6e7f1; // 左
		box-shadow: 0 0 40upx #d6e7f1; // 右
		color: #2e2e2e;
		font-weight: 300;

		image {
			width: 70upx;
			height: 70upx;
			padding: 10upx 28upx 0upx 10upx;

		}

	}

	.con-shop {
		height: 100upx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		span {
			padding-right: 10upx;
			color: #b5b5b5;
			font-size: 28upx;
		}

		.image-code {
			width: 42upx;
			height: 42upx;
			padding: 10upx 28upx 0upx 10upx;
		}
	}

	.bottom-box {
		width: 100%;
		background-color: #fff;
		margin-top: 18upx;
		border-radius: 20upx;
		padding: 20upx 30upx;
		box-shadow: 0 0 40upx #d6e7f1; // 左
		box-shadow: 0 0 40upx #d6e7f1; // 右
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: absolute;
		// margin-bottom: 20upx;
		bottom: 0;

		image {
			width: 34upx;
			height: 34upx;
			padding: 10upx 28upx 0upx 10upx;
		}

		.tab-num {
			background: #1c76f1;
			padding: 16upx 64upx;
			border-radius: 14upx;
			color: #fff;
			font-weight: 300;
			display: flex;
		}
	}

	::v-deep.u-calendar-month__days__day__select {
		border-radius: 50%;
	}

	// .dialog {
	// 	width: 600upx;
	// 	height: 460upx;
	// 	padding: 0 40upx;
	// 	border-radius: 10upx;
	// 	background-color: #FFF;
	// 	position: relative;

	// 	.close {
	// 		position: absolute;
	// 		right: 20upx;
	// 		top: 20upx;
	// 	}

	// 	.title {
	// 		height: 120upx;
	// 		font-size: 32upx;
	// 		text-align: center;
	// 		line-height: 120upx;
	// 	}

	// 	.input {
	// 		height: 80upx;
	// 		padding: 0 30upx;
	// 		border-radius: 10upx;
	// 		margin: 40upx 0 80upx;
	// 		border: 2upx solid #ddd;
	// 	}

	// 	.btn {
	// 		color: #FFF;
	// 		height: 80upx;
	// 		line-height: 80upx;
	// 		text-align: center;
	// 		border-radius: 10upx;
	// 		background-color: #2CA246;

	// 		&.disabled,
	// 		&:active {
	// 			opacity: 0.8;
	// 		}
	// 	}
	// }
</style>